import themeConfig from './theme'
let lessLoaded = false

// 页面间localStorage事件监听
window.addEventListener('storage', function (e) { // e只是一个传参
  // 获取被修改的键值
  if (e.key == 'theme') {
    themeChange(e.newValue)
  }
}, false)

var originalSetItem = localStorage.setItem
// 页面内localStorage事件监听
localStorage.setItem = function (key, newValue) {
  var setItemEvent = new Event('setItemEvent')
  setItemEvent.key = key
  setItemEvent.newValue = newValue
  window.dispatchEvent(setItemEvent)
  originalSetItem.apply(this, arguments)
}
window.addEventListener('setItemEvent', function (e) {
  if (e.key == 'theme') {
    themeChange(e.newValue)
  }
})

function themeChange (v) {
  let theme = v

  if (!theme) {
    return
  }
  // localStorage.theme = JSON.stringify(value)
  const changeColor = () => {
    window.less
      .modifyVars({
        ...themeConfig.varsOpt[theme]
      })
  }

  if (lessLoaded) {
    changeColor()
  } else {
    window.less = {
      async: true,
      javascriptEnabled: true
    }
    loadLessAndScript().then(() => {
      lessLoaded = true
      changeColor()
    })
  }
}

function loadLessAndScript () {
  return new Promise((resolve, reject) => {
    const link = document.createElement('link')
    link.rel = 'stylesheet/less'
    link.type = 'text/css'
    link.href = 'static/_less/color.less'
    document.head.appendChild(link)

    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'static/_less/less.min.js'
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}

export default themeChange
